#!/usr/bin/python

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# subversion info:
# $HeadURL: $
# $Author: $
# $Id: $
# $Revision: $

# External imports
import os.path
import urllib2
import feedparser
import HTMLParser

# Internal imports
from Model import TVSerie, Season, Episode, Event, DOWNLOADING

class Torrent(object):
  """
  Sphinx data.
  """

  properties = {
    'Show Name': 'show',
    'Season': 'season',
    'Episode': 'episode',
    'Episode Title': 'title'
  }
  
  htmlParser = HTMLParser.HTMLParser()

  def __init__(self, entry):
    super(Torrent, self).__init__()
    self.show = None
    self.season = None
    self.episode = None
    self.title = None
    self.link = None
    self.__parseEntry(entry)
    self.__postParse()
 
  def __parseEntry(self, entry):
    tokens = self.htmlParser.unescape(entry.summary).split('; ')
    summaryDict = {}
    for token in tokens:
      try:
        key, value = token.split(': ')
      except ValueError: # Malformed token
        continue
      attr = self.properties.get(key)
      if not attr: # Invalid property
        continue
      setattr(self, attr, value)
    self.link = entry.link

  def __postParse(self):
    try:
      self.season = int(self.season)
    except: # ValueError or TypeError
      pass
    try:
      self.episode = int(self.episode)
    except: # ValueError or TypeError
      pass

  def __repr__(self):
    return """
Show name: %s
Season: %s
Episode: %s
Episode title: %s
Links to: %s
""" % (self.show, self.season, self.episode, self.title, self.link)

  def download(self, torrentStore):
    print 'Downloading %s...' % self.link,
    oPath = os.path.join(torrentStore, os.path.basename(self.link))
    if os.path.exists(oPath):
      print 'Already downloaded. Done.'
      return False
    ofd = open(oPath, 'w')
    ifd = urllib2.urlopen(self.link)
    ofd.write(ifd.read())
    print 'Done.'
    return True


class Feed(object):
  """
  Sphinx data.
  """

  def __init__(self, config):
    super(Feed, self).__init__()
    self.__feedSource = 'http://ezrss.it/feed/'
    self.__torrentStore = config.get('torrentspath')
    self.__torrents = []
    self.__parse()

  def __parse(self):
    data = feedparser.parse(self.__feedSource)
    for entry in data.entries:
      # Reverse the list so its in chronological order
      self.__torrents.insert(0, Torrent(entry))

  def filterBy(self, show=None, season=None, episode=None, title=None, exists=False):
    for torrent in self.__torrents:
      if show is not None and torrent.show != show:
        continue
      if season is not None and torrent.season != season:
        continue
      if episode is not None and torrent.episode != episode:
        continue
      if title is not None and torrent.title != title:
        continue
      if not exists and os.path.exists(os.path.join(self.__torrentStore,
          os.path.basename(torrent.link))):
        continue
      yield torrent

  def download(self, torrents):
    for torrent in torrents:
      torrent.download(self.__torrentStore)

  def syncDB(self):
    filters = {}
    for tvSerie in TVSerie.select(TVSerie.q.active == True):
      print 'Syncing TV Serie %s...' % tvSerie.name
      filters[tvSerie.name] = tvSerie
    
    for torrent in self.__torrents:
      if torrent.show in filters:
        tvSerie = filters[torrent.show]
        if tvSerie.publisher and torrent.link.find(tvSerie.publisher) == -1:
          continue
        episode = tvSerie.addEpisode(
            torrent.season, torrent.episode, (torrent.title != 'N/A') and
            torrent.title or '', torrent.link)
        if episode:
          torrent.download(self.__torrentStore)
          codename = '%s.S%02dE%02d%s' % (tvSerie.name, torrent.season,
              torrent.episode, torrent.title and '.%s' % torrent.title or '')
          Event(title='New download %s' % codename,
              description='Downloading <a href="%s">%s</a>' % (torrent.link,
                codename),
              type=DOWNLOADING,
              episode=episode
            )

